package com.comp437.uno.view.playboard;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import android.R.color;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.comp437.uno.model.ClientService;
import com.comp437.uno.model.Model;
import com.comp437.uno.model.ClientService.LocalBinder;
import com.comp437.uno.view.login.Login;
import com.example.comp437uno.R;

@SuppressLint("DefaultLocale")
public class PlayBoard extends Activity {
	 TextView user1,user2,player;
	 TextView user1No,user2No;
	 static TextView playedCardInstruction;
	 static ImageView playedCard;
	 ImageView user1Card, user2Card;
	 Button bt_pass;
	 static LinearLayout playerCards,playerboard;
	 Model model;
	 boolean playing = true;
	 @SuppressLint("UseSparseArrays")
	static HashMap<Integer, Card>  cards = new HashMap<Integer, Card>();
	 boolean started=false;
	 private int cardid =0; 
	 public static Handler handler; 
		Intent service;
		
		ClientService cs;
		boolean myBound=false;
		
	  @SuppressLint("HandlerLeak")
	public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        model = Model.getModel();
	        setContentView(R.layout.playboard);
	        user1 = (TextView) findViewById(R.id.textview_playboard_user1_id);
	        user2 = (TextView) findViewById(R.id.textview_playboard_user2_id);
	        player = (TextView) findViewById(R.id.textview_playboard_player_id);
	        user1No = (TextView) findViewById(R.id.textview_playboard_user1_card_no);
	        user2No = (TextView) findViewById(R.id.textview_playboard_user2_card_no);
	        playedCardInstruction = (TextView) findViewById(R.id.textview_playboard_played_card_instruction);
	        
	        playedCard = (ImageView) findViewById(R.id.imageview_playboard_played_card);
	        user1Card = (ImageView) findViewById(R.id.imageview_playboard_user1_card);
	        user2Card = (ImageView) findViewById(R.id.imageview_playboard_user2_card);
	        
	        playerCards = (LinearLayout) findViewById(R.id.linearlayout_playboard_player_cards); 
	        playerboard = (LinearLayout) findViewById(R.id.linearlayout_playboard_player); 

	        bt_pass = (Button) findViewById(R.id.button_playboard_player_pass);

	        bt_pass.setOnClickListener(new passOnClickListener());
	      
	        bt_pass.setEnabled(false);
	    	service = new Intent(PlayBoard.this, ClientService.class);
	    	bindService(service, mConnection, Context.BIND_AUTO_CREATE);
	    	
	    	handler = new Handler(){ 
	    		 
	            @Override 
	            public void handleMessage(Message msg) { 
	                super.handleMessage(msg); 
	                switch(msg.what){
	                case 1:setTheCentralCard((String)msg.obj);break;
	                case 2:setPlayerUno();break;
	                case 3:setPlayerName((String)msg.obj);break;
	                case 4:setUser1Name((String)msg.obj);break;
	                case 5:setUser2Name((String)msg.obj);break;
	                case 6:setUser1CardNum(msg.arg1);break;
	                case 7:setUser2CardNum(msg.arg1);break;
	                case 8:
	                case 9:
	                case 10:setPlaying(msg.arg1==1);break;
	                case 11:setWin();break;
	                case 12:setLose();break;
	                case 13: update();break;
	               
	                }
	            } 
	             
	        }; 
	        model.putPlayBoard(this);
	        model.sendReady();
	 }
	  
	  public static void changeTheCentralCard(int id,String cardValue){
		  playedCard.setImageResource(id);
		  playedCardInstruction.setText(cardValue.toUpperCase());
	  }
	  /**
	   * This is for the model to use; 1
	   * @param cardValue
	   * 1
	   */
	  public void setTheCentralCard(String cardValue){
		  		if(cardValue.equalsIgnoreCase("pass"))
		  			return;
				String card= cardValue.toLowerCase();
		  		int cardImage;
				Field field;
				try {
					Log.i("PlayBoard",card);
					if(card.length()>2)
						field = this.getClass().getField(card.substring(0, 2));
					else
						field = this.getClass().getField(card);

					cardImage=field.getInt(this);
					changeTheCentralCard(cardImage,cardValue);
				} catch (NoSuchFieldException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
				
	  }
	  //2
	  public void setPlayerUno(){
		  playedCardInstruction.setText("You UNO!");
	  }
	  //3
	  public void setPlayerName(String userid){
		  player.setText(userid);
	  }
	  //4
	  /**
	   * Set user1 name
	   * @param user1Name
	   */
	  public void setUser1Name(String user1Name){
		  user1.setText(user1Name);
	  }
	  /**
	   * Set user2 Name
	   * @param user2Name
	   */
	  //5
	  public void setUser2Name(String user2Name){
		  user2.setText(user2Name);
	  }
	  /**
	   * Set user1 card num
	   * @param user1CardNum
	   */
	  //6
	  public void setUser1CardNum(int user1CardNum){
		  user1No.setText("Num:"+user1CardNum);
		  if(user1CardNum==1)
			  setUser1Uno(true);
		  else
			  setUser1Uno(false);
	  }
	  /**
	   * set user2 card num
	   * @param user2CardNum
	   */
	  //7
	  public void setUser2CardNum(int user2CardNum){
		  user2No.setText("Num:"+user2CardNum);
		  if(user2CardNum==1)
			  setUser2Uno(true);
		  else
			  setUser2Uno(false);
	  }
	  /**
	   * whether the user 1 is UNO
	   * @param uno
	   */
	  //8
	  private void setUser1Uno(boolean uno){
		  if(uno)
			  user1Card.setImageResource(R.drawable.uno);
		  else
			  user1Card.setImageResource(R.drawable.back);
	  }
	  /**
	   * Whether the user2 is uno
	   * @param uno
	   */
	  //9
	  private void setUser2Uno(boolean uno){
		  if(uno)
			  user2Card.setImageResource(R.drawable.uno);
		  else
			  user2Card.setImageResource(R.drawable.back);
	  }
	  /**
	   * Call this method if it is the player need to play the card@param p
	   */
	  //10
	  public void setPlaying(boolean p){
		  //Log.i("PlayBoard","I tried to set the playing :" + p);
		  Collection<Card> s = cards.values();
		  Iterator<Card> i = s.iterator();
		  if(p){
			  // let the player play, thus enable all the buttons
			  playerboard.setBackgroundColor(color.holo_red_dark);
			  bt_pass.setEnabled(p);
			  bt_pass.setOnClickListener(new passOnClickListener());
			  //Log.i("PlayBoard","I should Enable the pass button" + p);
			  while(i.hasNext())
				  i.next().setEnable(p);

		  }
		  else{
			  // player should not play, thus disable all the buttons
			  playerboard.setBackgroundColor(color.transparent);
			  bt_pass.setEnabled(p);
			  //Log.i("PlayBoard","I should Disable the pass button" + p);
			  bt_pass.setOnClickListener(null);
			  
			  while(i.hasNext())
				  i.next().setEnable(p);
		  }
	  }
	  /**
	   * Call this function if the player wins
	   */
	  //11
	  public void setWin(){
		  playedCard.setImageResource(R.drawable.win);
		  
		  started=false;
	  }
	  /**
	   * Call this function if the player loses
	   */
	  //12
	  public void setLose(){
		  playedCard.setImageResource(R.drawable.lose);
		  
		  started = false;
	  }
	  
	  /**
	   * Called by Card, no need to change 
	   * @param cardNum
	   */
	  public static void removeCard(int cardNum){
		 
		  playerCards.removeView(cards.get(cardNum));
	  }
	  
	@Override
	public void onBackPressed()
	{
		if(started)  
			model.showToast(this, "Not Allowed!");
		else
			super.onBackPressed();
	}
	  
	public void addCard(String card){
		String str=card.toLowerCase();
		cards.put(cardid, new Card(playerCards.getContext()).setCard(str, cardid));
		playerCards.addView(cards.get(cardid));
		//playedCardInstruction.setText("Add an Card");
		cardid++;
		
	}
	//13
	public void update(){
		playerCards.removeAllViews();
		ArrayList<String> cards = model.getCards();
		for(int i=0;i<cards.size();i++){
			addCard(cards.get(i));
		}
	}
	
	
	
	  class addOnClickListener implements android.view.View.OnClickListener{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub

			if(!started)
				playerCards.removeAllViews();
			started = true;
			cards.put(cardid, new Card(playerCards.getContext()).setCard("b"+cardid, cardid));
			playerCards.addView(cards.get(cardid));
			playedCardInstruction.setText("Add an Card");
			cardid++;
			
		}
		  
	  }
	  class passOnClickListener implements android.view.View.OnClickListener{

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				model.playCard("PASS");
				bt_pass.setEnabled(false);
				Log.i("PlayBoard","Pass Button Clicked!");
				//PlayBoard.super.onBackPressed();
				
			}
			  
	  }
	  
		
		private ServiceConnection mConnection = new ServiceConnection() {

	        @Override
	        public void onServiceConnected(ComponentName className,
	                IBinder service) {
	            // We've bound to LocalService, cast the IBinder and get LocalService instance
	            LocalBinder binder = (LocalBinder) service;
	            cs = binder.getService();
	            myBound = true;
	        }

	        @Override
	        public void onServiceDisconnected(ComponentName arg0) {
	            myBound = false;
	        }
	    };

	  
	    public final int b0=0x7f020000;
	    public final int b1=0x7f020001;
	    public final int b2=0x7f020002;
	    public final int b3=0x7f020003;
	    public final int b4=0x7f020004;
	    public final int b5=0x7f020005;
	    public final int b6=0x7f020006;
	    public final int b7=0x7f020007;
	    public final int b8=0x7f020008;
	    public final int b9=0x7f020009;
	    public final int back=0x7f02000a;
	    public final int background=0x7f02000b;
	    public final int bd=0x7f02000c;
	    public final int br=0x7f02000d;
	    public final int bs=0x7f02000e;
	    public final int g0=0x7f02000f;
	    public final int g1=0x7f020010;
	    public final int g2=0x7f020011;
	    public final int g3=0x7f020012;
	    public final int g4=0x7f020013;
	    public final int g5=0x7f020014;
	    public final int g6=0x7f020015;
	    public final int g7=0x7f020016;
	    public final int g8=0x7f020017;
	    public final int g9=0x7f020018;
	    public final int gd=0x7f020019;
	    public final int gr=0x7f02001a;
	    public final int gs=0x7f02001b;
	    public final int icon_user=0x7f02001c;
	    public final int inputbackground=0x7f02001d;
	    public final int join=0x7f02001e;
	    public final int login_bg=0x7f02001f;
	    public final int lose=0x7f020020;
	    public final int nojoin=0x7f020021;
	    public final int profile_bg=0x7f020022;
	    public final int r0=0x7f020023;
	    public final int r1=0x7f020024;
	    public final int r2=0x7f020025;
	    public final int r3=0x7f020026;
	    public final int r4=0x7f020027;
	    public final int r5=0x7f020028;
	    public final int r6=0x7f020029;
	    public final int r7=0x7f02002a;
	    public final int r8=0x7f02002b;
	    public final int r9=0x7f02002c;
	    public final int rd=0x7f02002d;
	    public final int roombackground=0x7f02002e;
	    public final int rr=0x7f02002f;
	    public final int rs=0x7f020030;
	    public final int settings=0x7f020031;
	    public final int tab_bg=0x7f020032;
	    public final int uno=0x7f020033;
	    public final int uno_icon=0x7f020034;
	    public final int uno_icon_lunchar=0x7f020035;
	    public final int user_smile=0x7f020038;
	    public final int win=0x7f020039;
	    public final int y0=0x7f02003a;
	    public final int y1=0x7f02003b;
	    public final int y2=0x7f02003c;
	    public final int y3=0x7f02003d;
	    public final int y4=0x7f02003e;
	    public final int y5=0x7f02003f;
	    public final int y6=0x7f020040;
	    public final int y7=0x7f020041;
	    public final int y8=0x7f020042;
	    public final int y9=0x7f020043;
	    public final int yd=0x7f020044;
	    public final int yr=0x7f020045;
	    public final int ys=0x7f020046;
	 
}
